package anton.admin.lunch;

import anton.admin.schema.Schema;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.sql.DataSource;

/**
 *
 * @author Joakim
 */

@ManagedBean(name = "lunchMenu")
@SessionScoped

public class LunchMenu implements Serializable {
       
    @Resource(name = "jdbc/antonsDatasource")
        private DataSource ds;
    
    //<editor-fold defaultstate="collapsed" desc="Vars required for date-functions">
    private SimpleDateFormat sdf;
    private Calendar cal;
    private String mondayDate;
    private int week;
    private List<String> weekDates;
    private int weekToday;
    private String dateToday;
    private String tempDate;
    //</editor-fold>
    
    private List<String> lunchNames;
    private List<LunchMenuEntity> lunches;
    private List<LunchMenuEntity> saveLunches;

    private String tempName;
    private int counter;
    private boolean menuEdit;
    private String menuDate;
    
    private int currentWeek;
    private int selectedWeek;
    
    public LunchMenu() {
        counter = 0;
        week = 0;
        sdf = new SimpleDateFormat("yyyy-MM-dd");
        setMondayDate();
        setWeekDates();
        cal = Calendar.getInstance();
        currentWeek = cal.get(Calendar.WEEK_OF_YEAR);
        
        lunches = new ArrayList<>();
        saveLunches = new ArrayList<>();
        lunchNames = new ArrayList<>();
        
        menuEdit = false;
    }
    
    public void readLunches() throws SQLException {
        
        Connection con = null;
        PreparedStatement ps = null;
        ResultSet result = null;
        saveLunches.clear();
        
        try {
            
            if(ds == null)
                throw new SQLException("Can't get datasource");
            
            con = ds.getConnection();
            
            if(con == null)
                throw new SQLException("Can't get database connection");
            
            ps = con.prepareStatement("SELECT lunch_name FROM Lunch");
            
            result = ps.executeQuery();
            
            while(result.next()) {
                LunchMenuEntity temp = new LunchMenuEntity();
                
                temp.setLunchName(result.getString("lunch_name"));
                temp.setLunchDate(null);
                        
                saveLunches.add(temp);
            }
            
        } finally {
            closeAll(result, ps, con);
        }
    }
    
    public void newMenu(String date)
    {
        menuEdit = true;
        menuDate = date;
    }
    
    public void loadDayLunches(int days){
        cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
        cal.add(Calendar.DAY_OF_YEAR, days);
        tempDate = sdf.format(cal.getTime());
        try {
            loadLunches(tempDate);
        } catch (SQLException ex) {
            Logger.getLogger(LunchMenu.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    public void loadLunches(String date) throws SQLException {
        Connection con = null;
        PreparedStatement ps = null;
        ResultSet result = null;
        lunches.clear();

        try {
            if (ds == null) 
                throw new SQLException("Can't get data source");

            con = ds.getConnection();

            if (con == null) 
                throw new SQLException("Can't get database connection");

            ps = con.prepareStatement("SELECT lunch_date, lunch_name FROM LunchMenu WHERE lunch_date=\"" + date + "\"");

            result = ps.executeQuery();

            while (result.next()) {
                LunchMenuEntity temp = new LunchMenuEntity();

                temp.setLunchDate(result.getString("lunch_date"));
                temp.setLunchName(result.getString("lunch_name"));

                lunches.add(temp);
            }
            
        } finally {
            closeAll(result, ps, con);
        }
    }
    
    public void saveEdit(String date) throws SQLException {
        
        Connection con = null;
        PreparedStatement ps = null;
        String insertName = null;
        
        try {
            if(ds == null)
                throw new SQLException("Can't get data source");
        
            con = ds.getConnection();
        
            if(con == null)
                throw new SQLException("Can't get database connection");
                
            for(Iterator<String> iter = lunchNames.iterator(); iter.hasNext(); ) {
                insertName = iter.next();
                
                ps = con.prepareStatement("INSERT INTO LunchMenu (lunch_date, lunch_name) VALUES (\"" + date + "\", \"" + insertName + "\")");
                ps.execute();
            }
        } finally {
            closeAll(null, ps, con);
        }
        
    }
    
    public void closeEdit()  {
        menuEdit = false;
    }
    
    public void removeMenu(String date) throws SQLException  {
        
        Connection con = null;
        PreparedStatement ps = null;
        
        try {
            if(ds == null)
                throw new SQLException("Can't get data source");
            
            con = ds.getConnection();
            
            if(con == null)
                throw new SQLException("Can't get database connection");
            
            ps = con.prepareStatement("DELETE FROM LunchMenu WHERE lunch_date=\"" + date + "\"");
            
            ps.execute();
            
        } finally {
            closeAll(null, ps, con);
        }
    }
    
    private static void closeAll(ResultSet resultSet, PreparedStatement preState, Connection con) {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
            }
        }
        if (preState != null) {
            try {
                preState.close();
            } catch (SQLException e) {
            }
        }
        if (con != null) {
            try {
                con.close();
            } catch (SQLException e) {
            }
        }
    }
    
    //<editor-fold defaultstate="collapsed" desc="Functions for date present in anton.admin.schema.Schema.java">
    private void setWeekDates() {
        weekDates = new ArrayList<>();
        for (int d = 0; d < 7; d++) {
            try {
                cal.setTime(sdf.parse(mondayDate));
            } catch (ParseException ex) {
                Logger.getLogger(Schema.class.getName()).log(Level.SEVERE, null, ex);
            }
            cal.add(Calendar.DATE, d);
            weekDates.add(sdf.format(cal.getTime()));
        }
    }
    
    public void nextWeek() {
        week += 1;
        selectedWeek +=1;
        setMondayDate();
        setWeekDates();
    }

    public void prevWeek() {
        week -= 1;
        selectedWeek -=1;
        setMondayDate();
        setWeekDates();
    }
    
    public int getWeek() {
        setMondayDate();
        setWeekDates();
        return cal.get(Calendar.WEEK_OF_YEAR);
    }

    public String getMondayDate() {
        return mondayDate;
    }

    private void setMondayDate() {
        cal = Calendar.getInstance();
        cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
        cal.add(Calendar.DATE, week * 7);
        this.mondayDate = sdf.format(cal.getTime());
    }
    
    public int getWeekToday() {
        cal = Calendar.getInstance();
        weekToday = cal.get(Calendar.WEEK_OF_YEAR);
        return weekToday;
    }

    public String getDateToday() {
        cal = Calendar.getInstance();
        dateToday = sdf.format(cal.getTime());
        return dateToday;
    }
    
    public List<String> getWeekDates() {
        return weekDates;
    }
    //</editor-fold>

    
    //<editor-fold defaultstate="collapsed" desc="Getters/setters">
    /**
     * @return the lunchName
     */
    public List<String> getLunchNames() {
        return lunchNames;
    }

    /**
     * @param lunchName the lunchName to set
     */
    public void setLunchNames(List<String> lunchName) {
        this.lunchNames = lunchName;
    }

    /**
     * @return the counter
     */
    public int getCounter() {
        return counter;
    }

    /**
     * @param counter the counter to set
     */
    public void setCounter(int counter) {
        this.counter = counter;
    }

    /**
     * @return the tempName
     */
    public String getTempName() {
        return tempName;
    }

    /**
     * @param tempName the tempName to set
     */
    public void setTempName(String tempName) {
        this.tempName = tempName;
    }

    /**
     * @return the lunches
     */
    public List<LunchMenuEntity> getLunches() {
        return lunches;
    }

    /**
     * @param lunches the lunches to set
     */
    public void setLunches(List<LunchMenuEntity> lunches) {
        this.lunches = lunches;
    }

    /**
     * @return the menuEdit
     */
    public boolean isMenuEdit() {
        return menuEdit;
    }

    /**
     * @param menuEdit the menuEdit to set
     */
    public void setMenuEdit(boolean menuEdit) {
        this.menuEdit = menuEdit;
    }

    /**
     * @return the saveLunches
     */
    public List<LunchMenuEntity> getSaveLunches() {
        return saveLunches;
    }

    /**
     * @param saveLunches the saveLunches to set
     */
    public void setSaveLunches(List<LunchMenuEntity> saveLunches) {
        this.saveLunches = saveLunches;
    }

    /**
     * @return the menuDate
     */
    public String getMenuDate() {
        return menuDate;
    }

    /**
     * @param menuDate the menuDate to set
     */
    public void setMenuDate(String menuDate) {
        this.menuDate = menuDate;
    }

    /**
     * @return the lunchName
     */
    //</editor-fold>
}
